package com.capinfo.accumulation.service.collection.impl;

import com.capinfo.accumulation.model.collection.Person;
import com.capinfo.accumulation.model.collection.PersonAccountFund;
import com.capinfo.accumulation.model.collection.PersonHistory;
import com.capinfo.accumulation.model.collection.PersonHistoryAccountFund;
import com.capinfo.accumulation.parameter.collection.PersonHistoryAccountFundParameter;
import com.capinfo.accumulation.service.collection.PersonAccountFundService;
import com.capinfo.accumulation.service.collection.PersonHistoryAccountFundService;
import com.capinfo.accumulation.service.collection.PersonService;
import com.capinfo.accumulation.service.collection.PersonUtilService;
import com.capinfo.commons.project.service.region.RegionService;
import com.capinfo.framework.service.impl.CommonsDataOperationServiceImpl;
import com.capinfo.framework.util.LogUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by zhangxu on 2017/9/27.
 */
public class PersonHistoryAccountFundServiceImpl extends CommonsDataOperationServiceImpl<PersonHistoryAccountFund, PersonHistoryAccountFundParameter> implements PersonHistoryAccountFundService {

    private static final Log logger = LogFactory.getLog(RegionService.class);

    @Autowired
    private PersonService personService;

    @Autowired
    PersonUtilService utilService;
    @Autowired
    PersonAccountFundService personAccountFundService;

    @Override
    public PersonHistoryAccountFund saveOrUpdate(PersonHistoryAccountFundParameter parameter) {

        PersonHistoryAccountFund personHistoryAccountFund = parameter.getEntity();  //个人历史公积金
        Class<PersonHistoryAccountFund> entityClazz = parameter.getEntityClazz();

        PersonHistory personHistory = parameter.getEntityPerson();  //个人历史信息
        Class<PersonHistory> entityPersonClazz = parameter.getEntityPersonClazz();

        String supplementaccountNumber; //补充账号
        String accountNumber;   //基本账号

        PersonHistoryAccountFund personHistoryAccount = new PersonHistoryAccountFund();

        //获取开户的类型（基本补充）
        String extra = parameter.getExtra();

        Long id = parameter.getId();

        if (parameter.getIsFirstSave() == 0) {      //新增
            if (extra == null ) {
                //个人基本账号
                accountNumber = utilService.generateBasePersonCode();
                personHistoryAccountFund.setAccountNumber(accountNumber);

                personHistoryAccountFund.setAccountTypeId(71L); //账户类型（基本）

                personHistory.getPersonHistoryAccountFunds().add(personHistoryAccountFund);

                getGeneralService().persist(personHistory); //新增
                personHistoryAccountFund.setPersonHistory(personHistory);
                return personHistoryAccountFund;

            } else {  //补充开户
                //根据id获取单个人公积金信息
                PersonAccountFund personAccount = getGeneralService().getObjectById(PersonAccountFund.class, personHistoryAccountFund.getId());
                supplementaccountNumber = utilService.generateSupplyPersonCode(personAccount.getAccountNumber());

                //单位缴存比例
                // TODO: 2017/11/1  调整属性
                BeanUtils.copyProperties(personAccount, personHistoryAccount, new String[]{"id", "openedDate", "accountType", "isPayment", "accountState", "companyCode", "lastYearBalance", "regularBalance", "currentBalance", "lastMonthPayment", "lastChangeBalanceDate", "totalRemit", "totalSupplementaryPayment", "totalSupplementaryPaymentCo", "totalWithdraw", "totalWithdrawCount", "totalInterest", "totalAdjustment", "totalAdjustmentCount", "currentYearPayment", "currentYearPayFees", "currentYearPayFeesCount", "currentYearDraw", "currentYearDrawCount", "currentYearAdjustmentAmount", "currentYearAdjustmentCount", "currentYearDemandCardinal", "currentYearRegularCardinal", "monthAdjustmeYearInterest", "state", "remitState", "closeDate", "closeReason", "newOpenFlag", "fisrtRemitMonth", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHistoryId", "personHistory"});
                BeanUtils.copyProperties(personHistoryAccountFund, personHistoryAccount, new String[]{"id", "personAccountFundId", "companyAccountFundId", "personId", "openedDate", "accountTypeId", "accountType", "isPayment", "accountState", "companyCode", "lastYearBalance", "regularBalance", "currentBalance", "lastMonthPayment", "lastChangeBalanceDate", "totalRemit", "totalSupplementaryPayment", "totalSupplementaryPaymentCo", "totalWithdraw", "totalWithdrawCount", "totalInterest", "totalAdjustment", "totalAdjustmentCount", "currentYearPayment", "currentYearPayFees", "currentYearPayFeesCount", "currentYearDraw", "currentYearDrawCount", "currentYearAdjustmentAmount", "currentYearAdjustmentCount", "currentYearDemandCardinal", "currentYearRegularCardinal", "monthAdjustmeYearInterest", "state", "remitState", "closeDate", "closeReason", "newOpenFlag", "fisrtRemitMonth", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHistoryId", "personHistory", "person", "companyAccountFund", "personAccountFund", "previousId", "previous", "accountNumber"});
                personHistoryAccount.setCompanyAccountFund(null);
                personHistoryAccount.setAccountNumber(supplementaccountNumber);
                personHistoryAccount.setAccountTypeId(72L);
                getGeneralService().persist(personHistoryAccount);
                return personHistoryAccount;
            }
        } else{
            //获取个人公积金
            PersonHistoryAccountFund entityAccount = getGeneralService().getObjectById(entityClazz, id);
            //获取个人历史
            PersonHistory personHistoryBack = getGeneralService().getObjectById(entityPersonClazz, entityAccount.getPersonHistoryId());
            //根据个人公积金ID PersonHistoryAccountFundId查询
            //表单提交的不过滤，表单不提交的过滤掉
            BeanUtils.copyProperties(personHistoryAccountFund, entityAccount, new String[]{"id", "openedDate", "accountType", "isPayment", "accountState", "companyCode", "lastYearBalance", "regularBalance", "currentBalance", "lastMonthPayment", "lastChangeBalanceDate", "totalRemit", "totalSupplementaryPayment", "totalSupplementaryPaymentCo", "totalWithdraw", "totalWithdrawCount", "totalInterest", "totalAdjustment", "totalAdjustmentCount", "currentYearPayment", "currentYearPayFees", "currentYearPayFeesCount", "currentYearDraw", "currentYearDrawCount", "currentYearAdjustmentAmount", "currentYearAdjustmentCount", "currentYearDemandCardinal", "currentYearRegularCardinal", "monthAdjustmeYearInterest", "state", "remitState", "closeDate", "closeReason", "newOpenFlag", "fisrtRemitMonth", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHistoryId", "personHistory"});
            BeanUtils.copyProperties(personHistory, personHistoryBack, new String[]{"id", "personId", "nameAllPinYin", "gbsex", "sex", "gbmaritalStatus", "maritalStatus", "postCode", "gbidCardType", "idCardType", "gbeducation", "educationId", "education", "homeAddress", "fixedTelephoneNumber", "mobilePhone", "gbprofession", "profession", "gbtitle", "title", "gbpositionalTitle", "positionalTitle", "homeMonthlyIncome", "isFreeze", "loanState", "timeControl", "reserve", "newFlag", "customerNumber", "societyCardNo", "manageState", "companyPaymentRatio", "personPaymentRatio", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHisttoryAccountId", "personHistoryAccountFunds",});

            getGeneralService().update(personHistoryBack);
            entityAccount.setPersonHistory(personHistoryBack);
            return entityAccount;
        }
    }

    @Override
    public PersonHistory changeSaveOrUpdate (PersonHistoryAccountFundParameter parameter){

        //获取表单提交的数据
        PersonHistory personHistory = parameter.getEntityPerson();
        Class<PersonHistoryAccountFund> entityClazz = parameter.getEntityClazz();
        Class<PersonHistory> entityPersonClazz = parameter.getEntityPersonClazz();

        Long id = personHistory.getId();
        if (id != null) {
            try {
                //获取个人历史
                PersonHistory entityPersonHistory = getGeneralService().getObjectById(entityPersonClazz, id);
                getGeneralService().clear();
                BeanUtils.copyProperties(personHistory, entityPersonHistory, new String[]{"previousId", "companyId", "personalAccount", "id", "personId", "nameAllPinYin", "gbsex", "sex", "gbmaritalStatus", "maritalStatus", "postCode", "gbidCardType", "idCardType", "gbeducation", "educationId", "education", "homeAddress", "fixedTelephoneNumber", "mobilePhone", "gbprofession", "profession", "gbtitle", "title", "gbpositionalTitle", "positionalTitle", "homeMonthlyIncome", "isFreeze", "loanState", "timeControl", "reserve", "newFlag", "customerNumber", "societyCardNo", "manageState", "companyPaymentRatio", "personPaymentRatio", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHisttoryAccountId", "personHistoryAccountFunds",});
                entityPersonHistory.setPreviousId(id);
                entityPersonHistory.setPersonId(personHistory.getPersonId());

                //个人历史新增一条记录（第一次保存）
                if (parameter.getIsFirstSave() == 0) {
                    entityPersonHistory.setId(null);
                    getGeneralService().persist(entityPersonHistory);
                    parameter.setIsFirstSave(1);
                } else {
                    //个人历史更新记录（）
                    entityPersonHistory.setId(parameter.getPreviousId());
                    getGeneralService().update(entityPersonHistory);

                }
                return entityPersonHistory;

            } catch (Exception e) {
                LogUtils.debugException(logger, e);
                throw e;
            }
        } else {
            return null;
        }
    }

    @Override
    public Person changeAudit (PersonHistoryAccountFundParameter parameter){

        PersonHistory personHistory = parameter.getEntityPerson();
        Class<PersonHistory> entityPersonClazz = parameter.getEntityPersonClazz();
        //个人表最新id
        Long personHistoryId = parameter.getPreviousId();

        PersonHistory objectById = getGeneralService().getObjectById(PersonHistory.class, personHistoryId);
        try {
            Person person = getGeneralService().getObjectById(Person.class, objectById.getPersonId());
//            BeanUtils.copyProperties(personHistory,person,new String [] {"id", "personId","personalAccount", "nameAllPinYin", "gbsex", "sex", "gbmaritalStatus", "maritalStatus", "postCode", "gbidCardType", "idCardType", "gbeducation", "educationId", "education", "homeAddress", "fixedTelephoneNumber", "mobilePhone", "gbprofession", "profession", "gbtitle", "title", "gbpositionalTitle", "positionalTitle", "homeMonthlyIncome", "isFreeze", "loanState", "timeControl", "reserve", "newFlag", "customerNumber", "societyCardNo", "manageState", "companyPaymentRatio", "personPaymentRatio", "dateTime", "bankCode", "operatorId", "regionId", "siteId", "confirmerId", "confirmationTime", "channels", "createName", "personHisttoryAccountId", "personHistoryAccountFunds",});

            person.setName(objectById.getName());
            person.setSexId(objectById.getSexId());
            person.setIdCardTypeId(objectById.getIdCardTypeId());
            person.setIdCardNumber(objectById.getIdCardNumber());
            person.setBirthYearMonth(objectById.getBirthYearMonth());
            person.setKoseki(objectById.getKoseki());
            person.setHistoryId(objectById.getPersonId());


            getGeneralService().update(person);

            //更新历史表中previousId
//            PersonHistory entityPersonHistory = getGeneralService().getObjectById(entityPersonClazz,personHistory.getId());
//            BeanUtils.copyProperties(personHistory,entityPersonHistory,new String []{"previous"});
//            getGeneralService().update(entityPersonHistory);

        } catch (Exception e) {

            LogUtils.debugException(logger, e);
            throw e;
        }
        return null;
    }

}
